package top.yxqz.spring.transaction.annotation.dao.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import top.yxqz.spring.transaction.annotation.dao.BookDao;

/**
 * @author: 余小小
 * @date: 2023/4/20
 * @description：持久层
 */
@Repository("bookDao")
public class BookDaoImpl implements BookDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 通过图书id得到图书价格
     *
     * @param bookId
     * @return
     */
    @Override
    public Integer getPriceByBook(Integer bookId) {
        return jdbcTemplate.queryForObject(sql, Integer.class, bookId);
    }

    String sql = "select price from t_book  where book_id =?";
    /**
     * 更新库存 ，一次只买一本书
     *
     * @param bookId
     */
    @Override
    public void updateStock(Integer bookId) {
        String sql = "update t_book set stock = stock - 1 where book_id =?";
        jdbcTemplate.update(sql, bookId);
    }

    /**
     * 更新用户余额
     *
     * @param userId
     * @param price
     */
    @Override
    public void updateBalance(Integer userId, Integer price) {
        String sql = "update t_book_user set balance=balance -? where user_id =?";
        jdbcTemplate.update(sql, price, userId);
    }
}
